package com.pctx.bibatracker.service.impl;

import com.pctx.bibacommon.result.Result;
import com.pctx.bibacommon.util.UuidUtil;
import com.pctx.bibatracker.dao.*;
import com.pctx.bibatracker.pojo.*;
import com.pctx.bibatracker.service.PositionService;
import com.pctx.bibatracker.util.CoordinateTransforToGaoDe;
import com.pctx.bibatracker.util.CoordinateTransform;
import com.pctx.bibatracker.util.MathUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service("/positionService")
public class PositionServiceImpl implements PositionService {
    @Autowired
    private PositionMapper positionMapper;
    @Autowired
    private HistoryPositionMapper historyPositionMapper;
    @Autowired
    private FenceMapper fenceMapper;
    @Autowired
    private FenceOutInMapper fenceOutinMapper;
    @Autowired
    private AlarmMapper alarmMapper;

    /**
     * 调GPS传回来的数据
     *
     * @param cord_x
     * @param cord_y
     * @param cord_z
     * @param deviceNo
     * @return
     * @throws Exception
     */
    @Override
    public Result getPosition(BigDecimal cord_x, BigDecimal cord_y, BigDecimal cord_z, String deviceNo) throws Exception {
        if (StringUtils.isEmpty(deviceNo)) {
            return Result.error("参数不能为空");
        }
        Position positions = new Position();
        Double cordone = null;
        Position position = positionMapper.selectByDeviceUuid(deviceNo);
        HistoryPosition historyPosition = new HistoryPosition();
        FenceOutIn fenceOutIn = new FenceOutIn();
        Alarm alarm = new Alarm();
        int k=1;
        if (position != null) {
            position.setUuid(UuidUtil.randomUUID());
            position.setCordX(cord_x);
            position.setCordY(cord_y);
            position.setCordZ(cord_z);
            position.setCordType((byte) 0);
            position.setDeviceUuid(deviceNo);
            Date date = new Date();
            position.setCreateTime(date);
            position.setUpdateTime(date);
            Boolean flag = positionMapper.updateByPrimaryKey(position) > 0;
            if (flag) {
                historyPosition.setUuid(UuidUtil.randomUUID());
                historyPosition.setCordX(cord_x);
                historyPosition.setCordY(cord_y);
                historyPosition.setCordZ(cord_z);
                historyPosition.setDeviceUuid(deviceNo);
                historyPosition.setCordType(position.getCordType());
                historyPosition.setCreateTime(date);
                historyPosition.setUpdateTime(date);
                Boolean result = historyPositionMapper.insertSelective(historyPosition) > 0;
                System.out.println(result);
                if (result) {
                    List<Fence> list = fenceMapper.selectBydeviceUuid(deviceNo);
                    if (list.size() == 0) {
                        return Result.success("历史位置获取成功");
                    } else {
                        System.out.println(list.size() + "=======+++++");
                        for (Fence fence : list) {
                            System.out.println(fence.getCordType());
                            System.out.println(fence.getCordType());
                            if (fence.getCordType().equals((byte) 1)) {
                                String cord = CoordinateTransform.getCoordinate(cord_x, cord_y);
                                System.out.println(cord);
                                JSONObject jsonObjectone = JSONObject.fromObject(cord);
                                JSONArray jsonArrays = jsonObjectone.getJSONArray("result");
                                System.out.println(jsonArrays);
                                Map map = new HashMap();
                                ArrayList listTwo = new ArrayList();
                                Object[] os = jsonArrays.toArray();
                                for (int i = 0; i < os.length; i++) {
                                    JSONObject jsonObj = JSONObject.fromObject(os[i]);
                                    listTwo.add(jsonObj.get("x"));
                                    System.out.println(jsonObj.get("x"));
                                    listTwo.add(jsonObj.get("y"));
                                    System.out.println(jsonObj.get("y"));
                                }
                                BigDecimal wgs_x = MathUtils.getBigDecimal(listTwo.get(0)).setScale(12, BigDecimal.ROUND_HALF_UP);
                                BigDecimal wgs_y = MathUtils.getBigDecimal(listTwo.get(1)).setScale(12, BigDecimal.ROUND_HALF_UP);
                                cordone = CoordinateTransform.getDistanceFromTwoPoints(fence.getCordX().doubleValue(), fence.getCordY().doubleValue(), wgs_x.doubleValue(), wgs_y.doubleValue());
                                System.out.println(cordone);
                            } else if (fence.getCordType().equals((byte) 2)) {
                                ArrayList listFour = new ArrayList();
                                String cord = CoordinateTransforToGaoDe.getCoordinate(cord_x, cord_y);
                                JSONObject jsonObject = JSONObject.fromObject(cord);
                                String[] h = jsonObject.get("locations").toString().split(",");
                                for (int i = 0; i < h.length; i++) {
                                    listFour.add(h[i]);
                                }
                                BigDecimal wgs_x = MathUtils.getBigDecimal(listFour.get(0)).setScale(12, BigDecimal.ROUND_HALF_UP);
                                BigDecimal wgs_y = MathUtils.getBigDecimal(listFour.get(1)).setScale(12, BigDecimal.ROUND_HALF_UP);
                                cordone = CoordinateTransform.getDistanceFromTwoPoints(fence.getCordX().doubleValue(), fence.getCordY().doubleValue(), wgs_x.doubleValue(), wgs_y.doubleValue());
                                System.out.println(cordone + "-----");
                            }
                            System.out.println(cordone);
                            Long distens = cordone.longValue();
                            System.out.println(fence.getRadius() + "米+++++");
                            if (distens >= fence.getRadius()) {
                                fenceOutIn.setUuid(UuidUtil.randomUUID());
                                fenceOutIn.setDeviceUuid(deviceNo);
                                fenceOutIn.setFenceUuid(fence.getUuid());
                                fenceOutIn.setStatus((byte) 1);
                                fenceOutIn.setCreateTime(date);
                                fenceOutIn.setUpdateTime(date);
                                fenceOutIn.setRemark("aa");
                                Boolean a = fenceOutinMapper.insertSelective(fenceOutIn) > 0;
                                if (a) {
                                    //判断该围栏是什么报警类型
                                    if (fence.getInAlarm().equals(1)) {
                                        List<FenceOutIn> lists = fenceOutinMapper.selectAll(deviceNo);
                                        System.out.println(lists.size()+"++++++");
                                        if (lists.size() > 1) {
                                            System.out.println(k+"???????");
                                            if (lists.get(k).getStatus().equals((byte) 0)) {
                                                System.out.println("00000");
                                                alarm.setUuid(UuidUtil.randomUUID());
                                                alarm.setDeviceUuid(deviceNo);
                                                alarm.setType((byte) 1);
                                                alarm.setAlarmCode((byte) 0);
                                                alarm.setDescription("你的设备已走出安全区域");
                                                alarm.setCreateTime(date);
                                                alarm.setUpdateTime(date);
                                                alarm.setRemark("aa");
                                                Boolean resultone = alarmMapper.insertSelective(alarm) > 0;
                                                k++;
                                            } else if (lists.get(1).getStatus().equals((byte) 1)) {
                                                //return Result.success(fenceOutIn, "围栏进出表获取成功");
                                            }
                                        }
                                    } else if (fence.getInAlarm().equals(0)) {
                                        //return Result.success(fenceOutIn, "围栏进出表获取成功");
                                    } else {
                                        List<FenceOutIn> lists = fenceOutinMapper.selectAll(deviceNo);
                                        System.out.println(lists.size());
                                        if (lists.size() > 1) {
                                            System.out.println(k+"====="+lists.get(k).getStatus());
                                            if (lists.get(k).getStatus().equals((byte) 0)) {
                                                alarm.setUuid(UuidUtil.randomUUID());
                                                alarm.setDeviceUuid(deviceNo);
                                                alarm.setType((byte) 2);
                                                alarm.setAlarmCode((byte) 0);
                                                alarm.setDescription("你的设备已走出安全区域");
                                                alarm.setCreateTime(date);
                                                alarm.setUpdateTime(date);
                                                alarm.setRemark("aa");
                                                Boolean resultone = alarmMapper.insertSelective(alarm) > 0;
                                                k++;
                                            } else if (lists.get(1).getStatus().equals((byte) 1)) {
                                               // return Result.success(fenceOutIn, "围栏进出表获取成功");
                                            }
                                        }
                                    }
                                }
                            } else {
                                fenceOutIn.setUuid(UuidUtil.randomUUID());
                                fenceOutIn.setDeviceUuid(deviceNo);
                                fenceOutIn.setFenceUuid(fence.getUuid());
                                fenceOutIn.setStatus((byte) 0);
                                fenceOutIn.setCreateTime(date);
                                fenceOutIn.setUpdateTime(date);
                                fenceOutIn.setRemark("aa");
                                Boolean a = fenceOutinMapper.insertSelective(fenceOutIn) > 0;
                                if (a) {
                                    //判断该围栏是什么报警类型
                                    if (fence.getInAlarm().equals(0)) {
                                        List<FenceOutIn> lists = fenceOutinMapper.selectAll(deviceNo);
                                        System.out.println(lists.size());
                                        if (lists.size() > 1) {
                                            System.out.println(lists.get(k).getStatus()+"KKK"+k);
                                            if (lists.get(k).getStatus().equals((byte) 1)) {
                                                alarm.setUuid(UuidUtil.randomUUID());
                                                alarm.setDeviceUuid(deviceNo);
                                                alarm.setType((byte) 0);
                                                alarm.setAlarmCode((byte) 0);
                                                alarm.setDescription("你的设备已走出安全区域");
                                                alarm.setCreateTime(date);
                                                alarm.setUpdateTime(date);
                                                alarm.setRemark("aa");
                                                Boolean resultone = alarmMapper.insertSelective(alarm) > 0;
                                                k++;
                                                System.out.println(k);
                                            } else if (lists.get(1).getStatus().equals((byte) 0)) {
                                                //return Result.success(fenceOutIn, "围栏进出表获取成功");
                                            }
                                        }
                                    } else if (fence.getInAlarm().equals(1)) {
                                       // return Result.success(fenceOutIn, "围栏进出表获取成功");
                                    } else {
                                        List<FenceOutIn> lists = fenceOutinMapper.selectAll(deviceNo);
                                        System.out.println(lists.size());
                                        if (lists.size() > 1) {
                                            System.out.println(lists.get(1));
                                            if (lists.get(k).getStatus().equals((byte) 1)) {
                                                alarm.setUuid(UuidUtil.randomUUID());
                                                alarm.setDeviceUuid(deviceNo);
                                                alarm.setType((byte) 2);
                                                alarm.setAlarmCode((byte) 0);
                                                alarm.setDescription("你的设备已走出安全区域");
                                                alarm.setCreateTime(date);
                                                alarm.setUpdateTime(date);
                                                alarm.setRemark("aa");
                                                Boolean resultone = alarmMapper.insertSelective(alarm) > 0;
                                                k++;
                                            } else if (lists.get(1).getStatus().equals((byte) 0)) {
                                               // return Result.success(fenceOutIn, "围栏进出表获取成功");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //return Result.success(position, "设备位置获取成功");
                    }

                } else {
                    return Result.error("历史位置获取失败");
                }
            } else {
                return Result.error("位置获取失败");
            }
        } else {
            positions.setUuid(UuidUtil.randomUUID());
            positions.setCordX(cord_x);
            positions.setCordY(cord_y);
            positions.setCordZ(cord_z);
            positions.setCordType((byte) 0);
            positions.setDeviceUuid(deviceNo);
            Date date = new Date();
            positions.setUpdateTime(date);
            positions.setCreateTime(date);
            Boolean flag = positionMapper.insertSelective(positions) > 0;
            System.out.println(flag+"====================");
            if (flag) {
                System.out.println(flag+"====================");
                historyPosition.setUuid(UuidUtil.randomUUID());
                historyPosition.setCordX(cord_x);
                historyPosition.setDeviceUuid(deviceNo);
                historyPosition.setCordY(cord_y);
                historyPosition.setCordZ(cord_z);
                historyPosition.setCordType((byte) 0);
                historyPosition.setCreateTime(date);
                historyPosition.setUpdateTime(date);
                Boolean result = historyPositionMapper.insertSelective(historyPosition) > 0;
                System.out.println(result+"====================");
            }
        }
        return null;
    }

    /**
     * 定位（百度地图）
     *
     * @param device_uuid
     * @return
     * @throws Exception
     */
    @Override
    public Result getCurrentPosition(String device_uuid) throws Exception {
        if (StringUtils.isEmpty(device_uuid)) {
            return Result.error("参数不能为空");
        }
        Position position = positionMapper.selectByDeviceUuid(device_uuid);
        String cord = CoordinateTransform.getCoordinate(position.getCordX(), position.getCordY());
        System.out.println(cord + "+++++++---=====");
        JSONObject jsonObjectone = JSONObject.fromObject(cord);
        JSONArray jsonArrays = jsonObjectone.getJSONArray("result");
        System.out.println(jsonArrays + "+++++++---=====");
        /*ArrayList list = new ArrayList();
        Map map=new HashMap();
        Object[] os = jsonArrays.toArray();
        for (int i = 0; i < os.length; i++) {
            JSONObject jsonObj = JSONObject.fromObject(os[i]);
            list.add(jsonObj.get("x"));
            System.out.println(jsonObj.get("x"));
            list.add(jsonObj.get("y"));
            System.out.println(jsonObj.get("y"));
        }
        BigDecimal wgs_x = MathUtils.getBigDecimal(list.get(0)).setScale(12, BigDecimal.ROUND_HALF_UP);
        BigDecimal wgs_y = MathUtils.getBigDecimal(list.get(1)).setScale(12, BigDecimal.ROUND_HALF_UP);*/
        return Result.success(cord, "当前地理位置获取成功");
    }

    /**
     * 定位（高德地图）
     *
     * @param deviceNo
     * @return
     * @throws Exception
     */
    @Override
    public Result getCurrentPositionFromGaoDe(String deviceNo) throws Exception {
        if (StringUtils.isEmpty(deviceNo)) {
            return Result.error("参数不能为空");
        }
        Position position = positionMapper.selectByDeviceUuid(deviceNo);
        String cord = CoordinateTransforToGaoDe.getCoordinate(position.getCordX(), position.getCordY());
        System.out.println(cord);
        JSONObject jsonObject = JSONObject.fromObject(cord);
        Object result = jsonObject.get("locations");
        System.out.println(result);
        return Result.success(result, "当前地理位置获取成功");
    }


}
